﻿using System.Net;
using System.Reflection;
using System.Reflection.Emit;
using System.Text;
using rpc_service.cache;

namespace rpc_service.core.support.assembly.il;

public class ILWebRequest : ILUtil
{
    protected void createHttpWebRequest(ILGenerator il, string pathUrl, LocalBuilder requestLocal)
    {
        il.Emit(OpCodes.Ldstr, pathUrl);
        il.Emit(OpCodes.Call, "WebRequest".GetTypeByStr().GetMethod("Create", new[] { "string".GetTypeByStr() })!);
        il.Emit(OpCodes.Castclass, "HttpWebRequest".GetTypeByStr());
        il.Emit(OpCodes.Stloc, requestLocal);
    }
    
    protected void createHttpWebRequest(ILGenerator il, LocalBuilder pathUrl, LocalBuilder requestLocal)
    { 
        // 将 StringBuilder 转换为字符串
        il.Emit(OpCodes.Ldloc, pathUrl);
        il.Emit(OpCodes.Callvirt, "StringBuilder".GetTypeByStr().GetMethod("ToString", Type.EmptyTypes)!);
        
        // 创建 HttpWebRequest
        il.Emit(OpCodes.Call, "WebRequest".GetTypeByStr().GetMethod("Create", new[] { "string".GetTypeByStr() })!);
        il.Emit(OpCodes.Castclass, "HttpWebRequest".GetTypeByStr());
        il.Emit(OpCodes.Stloc, requestLocal);
    }
    
    protected void setRequestMethod(ILGenerator il, LocalBuilder requestLocal, String method)
    {
        il.Emit(OpCodes.Ldloc, requestLocal);
        il.Emit(OpCodes.Ldstr, method);
        il.Emit(OpCodes.Callvirt, "HttpWebRequest".GetTypeByStr().GetProperty("Method")!.SetMethod!);
    }

    protected void sendRequest(ILGenerator il, LocalBuilder requestLocal, LocalBuilder responseLocal)
    {
        il.Emit(OpCodes.Ldloc, requestLocal);
        il.Emit(OpCodes.Callvirt, "HttpWebRequest".GetTypeByStr().GetMethod("GetResponse")!);
        il.Emit(OpCodes.Castclass, "HttpWebResponse".GetTypeByStr());
        il.Emit(OpCodes.Stloc, responseLocal);
    }

    protected void getResponse(ILGenerator il, LocalBuilder responseLocal, LocalBuilder receiveStreamLocal)
    {
        il.Emit(OpCodes.Ldloc, responseLocal);
        il.Emit(OpCodes.Callvirt, "HttpWebResponse".GetTypeByStr().GetMethod("GetResponseStream")!);
        il.Emit(OpCodes.Stloc, receiveStreamLocal);
    }

    protected void returnData(ILGenerator il, LocalBuilder receiveStreamLocal, LocalBuilder readStreamLocal, LocalBuilder result)
    {        
        // 创建 StreamReader
        il.Emit(OpCodes.Ldloc, receiveStreamLocal);
        il.Emit(OpCodes.Ldstr, "UTF-8");
        il.Emit(OpCodes.Call, "Encoding".GetTypeByStr().GetMethod("GetEncoding", new[] { "string".GetTypeByStr() })!);
        il.Emit(OpCodes.Newobj, typeof(StreamReader).GetConstructor(new[] { typeof(Stream), typeof(Encoding) })!);
        il.Emit(OpCodes.Stloc, readStreamLocal);
        
        // 读取响应内容并输出
        il.Emit(OpCodes.Ldloc, readStreamLocal);
        il.Emit(OpCodes.Callvirt, typeof(StreamReader).GetMethod("ReadToEnd")!);
        il.Emit(OpCodes.Stloc, result);
    }
}